using UnityEngine;
using System.Collections;

public class ShootsBullets : MonoBehaviour {

	public GameObject bulletPrefab;

	public float attackSpeedModifier = 1f;

	public float attacksPerSecond {
		get {
			return bulletPrefab.GetComponent<BulletBehaviour>().bulletsPerSecond * attackSpeedModifier;
		}
	}

	float attackCooldown = 0;
	
	void Update() {
		attackCooldown -= Time.deltaTime;
	}

	public void Fire() {
		if(bulletPrefab == null) {
			Debug.LogError("No bullet prefab!");
			return;
		}

		if(attackCooldown > 0)
			return;

		attackCooldown = 1f / attacksPerSecond;

		GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, transform.position, transform.rotation);
		bulletGO.layer = this.gameObject.layer + 1;

		if(bulletGO.rigidbody2D==null) {
			Debug.LogError("No rigidbody2D on bullet!");
			return;
		}

		BulletBehaviour bb = bulletGO.GetComponent<BulletBehaviour>();
		bulletGO.rigidbody2D.velocity = this.transform.rotation * new Vector3(0, bb.bulletSpeed, 0);

		if(bb.bulletFireSound != null) {
			AudioSource.PlayClipAtPoint(bb.bulletFireSound, Vector3.zero, 0.2f);
		}

		if(GetComponent<Animator>() != null)
			GetComponent<Animator>().SetTrigger("Fire");
	}

}
